import { OrbitControls } from "three/examples/jsm/controls/OrbitControls.js"; //控制器
import * as THREE from "three";

const common = {
  // 初始化场景对象
  initScene: (model) => {
    model.scene = new THREE.Scene();
    // 创建三维坐标系
    model.axesHelper = new THREE.AxesHelper(0);
    model.scene.add(model.axesHelper);
  },
  // 初始化光源
  initLight: (model) => {
    model.light.hemiLight = new THREE.HemisphereLight(0xffffff, 0x000000, 1);
    model.light.hemiLight.position.set(0, 100, 0); //这个也是默认位置
    model.scene.add(model.light.hemiLight);
  },
  // 初始化相机
  initCamera: (model) => {
    model.camera = new THREE.PerspectiveCamera(
      45,
      model.container.offsetWidth / model.container.offsetHeight,
      0.1,
      1000
    );
    // 相机位置
    model.camera.position.set(120, 120, 120);
    // 设置相机指向的位置 默认0，0，0
    model.camera.lookAt(model.scene.position);
  },
  // 渲染器对象
  initRenderer: (model) => {
    model.renderer = new THREE.WebGLRenderer({
      antialias: true,
    });
    model.renderer.setSize(
      model.container.offsetWidth,
      model.container.offsetHeight
    );

    // 告诉渲染器需要阴影效果
    model.renderer.shadowMap.enabled = true;
    model.renderer.shadowMap.type = THREE.PCFSoftShadowMap;

    model.renderer.setClearColor(0xffffff, 0.1);
    model.container.appendChild(model.renderer.domElement);
  },
  // 控制器
  initControls: (model) => {
    model.controls = new OrbitControls(model.camera, model.renderer.domElement);
  },
  getScale: (fbx) => {
    const box3 = new THREE.Box3();
    box3.expandByObject(fbx); // 计算层级模型包围盒
    const v3 = new THREE.Vector3();
    // 获得包围盒长宽高尺寸，结果保存在参数三维向量对象v3中
    box3.getSize(v3);
    const S = 150 / num(v3);
    // 对模型进行缩放操作，实现全屏效果
    fbx.scale.set(S, S, S);
    const newBox3 = new THREE.Box3();
    newBox3.expandByObject(fbx);
    const center = new THREE.Vector3(); // 计算一个层级模型对应包围盒的几何体中心
    newBox3.getCenter(center);
    fbx.position.x = fbx.position.x - center.x;
    fbx.position.y = fbx.position.y - center.y;
    fbx.position.z = fbx.position.z - center.z;
  },
};

common.unwarp = (obj) => obj && (obj.__v_raw || obj.valueOf() || obj);

// 计算包围盒的最大边长
function num(v3) {
  let max;
  if (v3.x > v3.y) {
    max = v3.x;
  } else {
    max = v3.y;
  }
  if (max > v3.z) {
  } else {
    max = v3.z;
  }
  return max;
}

common.init3D = (model) => {
  common.initScene(model);
  common.initLight(model);
  common.initCamera(model);
  common.initRenderer(model);
};

export default common;
